﻿using IDal;
using MD5Hash;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dal
{
    public class UserDal : IUserDal
    {
        private readonly HotelDbContext db;

        public UserDal(HotelDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="userInfo">用户表</param>
        /// <returns>返回受影响行数</returns>
        public int Add(UserInfo userInfo)
        {
            //先通过账号进行查询
            IQueryable<UserInfo> list = db.Users.Where(x => x.UserName.Equals(userInfo.UserName));
            //获取到总条数
            if (list.Count() > 0)
            {
                //用户名已存在（记住一定是负整数）
                return -1;
            }
            else
            {
                //密码进行MD5加密
                userInfo.UserPwd = userInfo.UserPwd.GetMD5();
                db.Users.Add(userInfo);
                return db.SaveChanges();
            }

        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns>通过用户名和密码查询返回相应的值</returns>
        public dynamic Login(string name, string pwd)
        {
            IQueryable<UserInfo> list = db.Users;
            if (list.Count() > 0)
            {
                list = list.Where(x => x.UserName.Equals(name));
                if (list.Count() > 0)
                {
                    pwd = pwd.GetMD5();
                    list = list.Where(x => x.UserPwd.Equals(pwd));
                    if (list.Count() > 0)
                    {
                        return new
                        {
                            //登陆成功
                            number = 4,
                            row = list
                        };
                    }
                    return new
                    {
                        //密码不对
                        number = 3,
                        row = ""
                    };
                }
                return new
                {
                    //用户名不存在
                    number = 2,
                    row = ""
                };
            }
            return new
            {
                //请先去注册
                number = 1,
                row = ""
            };
        }
        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="name">姓名</param>
        /// <returns>通过登录人获取身份在获取信息</returns>
        public IQueryable<UserInfo> Show(string name = "")
        {
            UserInfo userInfo = db.Users.Where(x => x.UserName.Equals(name)).FirstOrDefault();
            if (userInfo.UserRole == "管理员")
            {
                return db.Users;
            }
            else
            {
                return db.Users.Where(x => x.UserName.Equals(name));
            }
        }
    }
}

